package co.edu.unal.satacredito.database.administration.ejb;

import java.net.UnknownHostException;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import org.bson.types.ObjectId;

import co.edu.unal.satacredito.database.administration.exceptions.DAOException;
import co.edu.unal.satacredito.database.administration.singleton.SingletonDataStore;
import co.edu.unal.satacredito.database.connection.MachineDatastoreFactory;
import co.edu.unal.satacredito.database.dao.FileLogMongoDao;
import co.edu.unal.satacredito.database.dao.MachineMongoDao;
import co.edu.unal.satacredito.database.entity.Machine;
import co.edu.unal.satacredito.database.entity.exceptions.NonexistentEntityException;
import co.edu.unal.satacredito.database.entity.exceptions.NullFieldEntityException;
import co.edu.unal.satacredito.database.entity.exceptions.PreexistingEntityException;

import com.mongodb.MongoException;

/**
 * Session Bean implementation class MachineDaoEJB
 */
@Stateless
public class MachineDaoEJB implements MachineDaoEJBRemote, MachineDaoEJBLocal {

	private MachineMongoDao daoM;
    /**
     * Default constructor. 
     * @throws DAOException 
     */
    public MachineDaoEJB() throws DAOException {
    	this.daoM = new MachineMongoDao(SingletonDataStore.getInstance()
				.getDataStore());		
    }

	@Override
	public List<Machine> findAllMachines() throws DAOException {
		try {
			return daoM.findAll();
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		}
	}

	@Override
	public void updateMachine(String id, Machine newMachine) throws DAOException {		
		try {
			daoM.update(new ObjectId(id), newMachine);
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		} catch (PreexistingEntityException e) {
			throw new DAOException(e.getMessage());
		} catch (NullFieldEntityException e) {
			throw new DAOException(e.getMessage());
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}		
	}

	@Override
	public Machine findByName(String name) throws DAOException {
		try {
			return daoM.findByMachineName(name);
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		}
	}

	@Override
	public void create(Machine newMachine) throws DAOException {
		try {
			daoM.create(newMachine);
		} catch (PreexistingEntityException e) {
			throw new DAOException(e.getMessage());
		}
	}

	@Override
	public Machine findByIp(String ip) {
			try {
				return daoM.findByIP(ip);
			} catch (NonexistentEntityException e) {
				return null;
			}
	}

}
